package com.example.bluetoothclicker

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.example.bluetoothclicker.db.SQLiteHelper
import com.example.bluetoothclicker.func.BluetoothConnectionManager

class RemoteFragment : Fragment() {

    private lateinit var dbHelper: SQLiteHelper
    private val buttonCommands = mutableMapOf<String, String>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.fragment_remote, container, false)

        // 初始化 SQLiteHelper
        dbHelper = SQLiteHelper(requireContext())

        // 获取按钮实例
        val forwardButton: Button = rootView.findViewById(R.id.forward_button)
        val leftButton: Button = rootView.findViewById(R.id.left_button)
        val rightButton: Button = rootView.findViewById(R.id.right_button)
        val backwardButton: Button = rootView.findViewById(R.id.backward_button)
        val stopButton: Button = rootView.findViewById(R.id.stop_button)
        val speedUpButton: Button = rootView.findViewById(R.id.speed_up_button)
        val speedDownButton: Button = rootView.findViewById(R.id.speed_down_button)

        // 加载数据库中的命令
        loadCommandsFromDatabase()

        // 绑定按钮点击事件
        forwardButton.setOnClickListener { sendCommandToCar(buttonCommands["FORWARD"] ?: "FORWARD") }
        leftButton.setOnClickListener { sendCommandToCar(buttonCommands["LEFT"] ?: "LEFT") }
        rightButton.setOnClickListener { sendCommandToCar(buttonCommands["RIGHT"] ?: "RIGHT") }
        backwardButton.setOnClickListener { sendCommandToCar(buttonCommands["BACKWARD"] ?: "BACKWARD") }
        stopButton.setOnClickListener { sendCommandToCar(buttonCommands["STOP"] ?: "STOP") }
        speedUpButton.setOnClickListener { sendCommandToCar(buttonCommands["SPEED_UP"] ?: "SPEED_UP") }
        speedDownButton.setOnClickListener { sendCommandToCar(buttonCommands["SPEED_DOWN"] ?: "SPEED_DOWN") }

        return rootView
    }

    /**
     * 从 SQLite 数据库加载命令
     */
    private fun loadCommandsFromDatabase() {
        try {
            buttonCommands.putAll(dbHelper.getAllCommands())
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(requireContext(), "加载命令失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 发送指令到小车
     * @param command 小车的指令，例如"FORWARD", "STOP"
     */
    private fun sendCommandToCar(command: String) {
        try {
            val bluetoothClient = BluetoothConnectionManager.getClient()
            bluetoothClient?.sendMessage(command) {
            }

        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(requireContext(), "发送失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
}
